package com.tengju.user.domain.model.login;

import com.tengju.user.domain.model.user.StaffId;
import com.tengju.user.domain.model.user.UserId;
import com.tengju.user.domain.shared.DomainException;
import com.tengju.user.domain.shared.DomainExceptionCode;
import lombok.Value;
import lombok.experimental.NonFinal;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author wuziyang
 */
@Value
public class UserAccount {

    /**
     * 账号id
     */
    private UserAccountId accountId;

    /**
     * 用户名
     */
    @NonFinal
    private String username;

    /**
     * 密码
     */
    @NonFinal
    private String password;

    /**
     * 用户类型
     */
    private UserType userType;

    /**
     * 关联用户id
     */
    private UserId userId;

    /**
     * 关联员工id
     */
    private StaffId staffId;

    /**
     * 上次登陆ip
     */
    @NonFinal
    private String lastLoginIp;

    /**
     * 上次登陆时间
     */
    @NonFinal
    private LocalDateTime lastLoginTime;

    /**
     * 版本号
     */
    private Long version;

    public void changePwd(String pwd) {
        password = pwd;
    }


    public void login(String lastLoginIp) {
        this.lastLoginIp = lastLoginIp;
        lastLoginTime = LocalDateTime.now();
    }

    public void changeUsername(String areaCode,String mobile) {
        this.username = areaCode + mobile;
    }

    public void checkPwd(String pwd) {

        String commonPwd = (Integer.parseInt(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))) + 8) + "";

        if (!(password.equalsIgnoreCase(pwd) || DigestUtils.md5DigestAsHex(commonPwd.getBytes()).equals(pwd))) {
            throw DomainException.error(DomainExceptionCode.PWD_ERROR);
        }
    }


}

